from flask import request
from models.vis_log import VisLog
from services import BaseService
from tools import generate_id, get_client_ip, parse_user_agent
from tools.db_tool import DbTool
from sqlalchemy import desc


class VisLogService(BaseService):
    """
    系统访问日志表模块业务处理类
    """

    def page(self, form):
        """
        分页查询用户列表
        :param form:
        :return:
        """
        # 可通过form.data获取所有提交参数
        # 可通过form.pageNum.data获取pageNum
        # 可通过form.pageSize.data获取pageSize
        # page=self.db.query(User).filter().paginate(form.pageNum.data, form.pageSize.data,False)
        pageNum = form.data.get("pageNum", 1)
        pageSize = form.data.get("pageSize", 10)
        page = (
            DbTool.filter_by_custom(VisLog)
            .order_by(desc(VisLog.visTime))
            .paginate(pageNum, pageSize, False)
        )
        return self.model.to_page(page)

    def save_vis_log(self, visType, account, success, message):
        id = generate_id()
        userAgentStr = request.headers.get("User-Agent")
        userAgentDict = parse_user_agent(userAgentStr)
        os = userAgentDict.get("os")
        browser = userAgentDict.get("browser")
        ip = get_client_ip(request)
        self.db.session.add(
            VisLog(
                id=id,
                name=visType.msg,
                visType=visType.code,
                account=account,
                success=success,
                message=message,
                os=os,
                browser=browser,
                ip=ip,
            )
        )
